package com.zzyang.c2c.social.govern.report.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.zzyang.c2c.social.govern.report.domain.ReportTask;
import com.zzyang.c2c.social.govern.report.domain.ReportTaskVote;
import com.zzyang.c2c.social.govern.report.service.ReportTaskService;
import com.zzyang.c2c.social.govern.report.service.ReportTaskVetoService;
import com.zzyang.c2c.social.govern.reviewer.api.ReviewerService;
import com.zzyang.c2c.social.govern.reward.api.RewardService;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 举报服务
 *
 * @author zhuoziyang
 * @date 2021/2/12 23:47
 */
@RestController
@RequestMapping("/report")
public class ReportController {

    @Reference(cluster = "failfast")
    private ReviewerService reviewerService;

    @Reference(cluster = "failfast")
    private RewardService rewardService;


    @Autowired
    private ReportTaskService reportTaskService;

    @Autowired
    private ReportTaskVetoService reportTaskVetoService;

    @GetMapping("/add")
    @SentinelResource("/addReportTask")
//    @GlobalTransactional
    public String add(@ModelAttribute ReportTask reportTask) {
        //插入任务
        reportTaskService.addReportTask(reportTask);

        //调用评审员服务查找评审员id
        List<Long> reviewerIds = reviewerService.selectReviewers(reportTask.getId());

        int i = 1 / 0;

        reportTaskVetoService.initVote(reviewerIds, reportTask.getId());

        return "success";
    }

    @GetMapping("/query/{id}")
    @SentinelResource("/queryReportTask")
    public ReportTask queryById(@PathVariable("id") Long id) {
        return reportTaskService.queryById(id);
    }

    @GetMapping("/vote")
    public String vote(@RequestParam("reviewerId") Long reviewerId,
                       @RequestParam("reportTaskId") Long reportTaskId,
                       @RequestParam("voteResult") Integer voteResult) {
        ReportTaskVote reportTaskVote = new ReportTaskVote();
        reportTaskVote.setReviewerId(reviewerId)
                .setReportTaskId(reportTaskId)
                .setVoteResult(voteResult);
        reportTaskVetoService.vote(reportTaskVote);

        reviewerService.finishVote(reviewerId, reportTaskId);

        boolean hasFinished = reportTaskVetoService.calculateVotes(reportTaskId);
        if (hasFinished) {
            List<ReportTaskVote> reportTaskVotes = reportTaskVetoService.queryByReportTaskId(reportTaskId);
            List<Long> reviewerIs = reportTaskVotes.stream().map(ReportTaskVote::getReviewerId).collect(Collectors.toList());
            rewardService.rewardReviewers(reviewerIs);
        }

        return "success";
    }

}
